package com.fj.springdataelasticsearch.demos.web;

import cn.hutool.core.util.RandomUtil;
import com.fj.springdataelasticsearch.demos.dao.ArticleRepository;
import com.fj.springdataelasticsearch.demos.domain.Article;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @author fj
 * @date 2024/3/19 09:44
 */
@AllArgsConstructor
@RestController
@RequestMapping(value = "article")
public class ArticleController {

    private final ArticleRepository articleRepository;

    @PostMapping
    public Article save(@RequestBody Article article){
        return articleRepository.save(article);
    }

    @GetMapping(value = "{id}")
    public Article get(@PathVariable(value = "id") Integer id){
        return articleRepository.findById(id).get();
    }

    @GetMapping(value = "page")
    public Page<Article> get(@RequestParam(value = "page") Integer page,@RequestParam(value = "size") Integer size){
        PageRequest pageRequest = PageRequest.of(page, size);
        return articleRepository.findAll(pageRequest);
    }

    @PostMapping(value = "buildTestData")
    public String buildTestData(){
        Set<Article> set = new HashSet<>(10000);
        for (int i=1;i<=10000;i++){
            String title = RandomUtil.randomString(6);
            String author = RandomUtil.randomString(4);
            String description = RandomUtil.randomString(200);
            set.add(new Article(i+"", title, description, author, RandomUtil.randomDouble(20,100),new Date(),RandomUtil.randomInt(100000,999999)));
        }
        Iterable<Article> articles = articleRepository.saveAll(set);
        return "ok";
    }
}
